package net.asfun.jvalog.domain;

import java.util.Collection;
import java.util.Date;

import javax.jdo.Query;

import com.google.appengine.api.datastore.Text;

import net.asfun.jvalog.service.Jdoer;
import net.asfun.jvalog.service.JdoerFactory;
import net.asfun.jvalog.po.Store;

public class Dbcache {
	
	private static long hits = 0;
	private static long misses = 0;
	private static long byteFetched = 0;
	private static long byteStored = 0;
	private static long items;
	
	static {
		Jdoer<Store> dbs = JdoerFactory.getStoreJdo();
		Collection<Store> stores = dbs.all();
		items = stores.size();
	}

	public static void clear() {
		Jdoer<Store> dbs = JdoerFactory.getStoreJdo();
		Collection<Store> stores = dbs.all();
		dbs.delete(stores);
		hits = 0;
		misses = 0;
		byteFetched = 0;
		byteStored = 0;
		items = 0;
	}

	public static String get(String key) {
		Store store = fetch(key);
		if ( store == null ) {
			misses++;
			return null;
		}
		store.count();
		hits++;
		byteFetched += store.getValue().getValue().getBytes().length;
		return store.getValue().getValue();
	}
	
	private static Store fetch(String key) {
		Jdoer<Store> dbs = JdoerFactory.getStoreJdo();
		Query query = dbs.prepareQuery();
		query.setFilter("item == akey");
		query.declareParameters("String akey");
		return dbs.unique(query, key);
	}

	public static void put(String key, String value) {
		byteStored += value.getBytes().length;
		Store store = fetch(key);
		if( store == null ) {
			Jdoer<Store> dbs = JdoerFactory.getStoreJdo();
			store = new Store();
			store.setDate(new Date());
			store.setItem(key);
			store.setValue(new Text(value));
			dbs.save(store);
			items++;
		} else {
			store.setDate(new Date());
			store.setValue(new Text(value));
		}
	}
	
	public static String stat() {
		StringBuffer buff = new StringBuffer();
		buff.append("Hits: ").append(hits)
			.append("\nMisses: ").append(misses)
			.append("\nBytes Fetched: ").append(byteFetched)
			.append("\nBytes Stored: ").append(byteStored)
			.append("\nItems: ").append(items)
			.append("\nMax Cached Time: N/A");
		return buff.toString();
	}

}
